<?php
namespace app\controller;

use app\BaseController;
use app\controller\model\Tables;
use liliuwei\think\Auth;
use EasyDingTalk\Application;
use think\facade\Db;
use think\facade\Session;

class Adminauth extends BaseController
{
	protected $tables;
	public function __construct(){
		checkuser();
		$this->gobaluser=Session::get("uid");
		$this->tables=new Tables();
	}
	public function getHomeList(){
		//{supplierID: $supplierID,serviceID:$serviceID,date1:$date1,date2:$date2}
		$supplierID = request()->param("supplierID");
		$serviceID = request()->param("serviceID");
		$gasID = request()->param("gasID");
		$date1 = request()->param("date1");
		$date2 = request()->param("date2");
		$admin = r_user($this->gobaluser);
		$isAdmin=true;
		if($date1=='' || $date2==''){
			$date1 = nowDate();
			$date2 = $date1 ;
		}
		//订单总数，默认今天的 总金额，优惠金额，结算金额=总金额-优惠金额
		$res = DB::name($this->tables->orders)->where("addTime",">=",$date1." 00:00:00")->where("addTime","<=",$date2." 23:59:59")->where("status",">",2);
		$res2 = DB::name($this->tables->serviceOrder)->where("addTime",">=",$date1." 00:00:00")->where("addTime","<=",$date2." 23:59:59")->where("status",">=",1);
		if($gasID>0){
			$res = $res->where("gasID",$gasID);
			$res2 = $res->where("gasID",$gasID);
		}
		if($serviceID>0){
			$res = $res->where("serviceID",$serviceID);
		}
		if($supplierID>0){
			$res = $res->where("supplierID",$supplierID);
			$res2 = $res->where("supplierID",$supplierID);
		}
		if($admin['ctype']==2 || $admin['ctype']==0){//油站管理员 只统计自营的 油站数据
			$res = $res->field("count(*) as a1,sum(amount) as a2,sum(sale) as a3")->find();
			$res['a4'] = bcsub($res['a2'],$res['a3'],2);
		}
		if($admin['ctype']==1 || $admin['ctype']==0){//服务商后台 只统计服务商的 油站数据
			$res2 = $res2->field("count(*) as a5,sum(amount) as a6,sum(salePrice) as a7")->find();
			$res2['a8'] = bcsub($res2['a6'],$res2['a7'],2);
		}
		foreach ($res as &$v){
			$v = number_format($v*1,2);
		}
		foreach ($res2 as &$v){
			$v = number_format($v*1,2);
		}
		if($admin['ctype']==1)echojson($res);
		if($admin['ctype']==2)echojson($res2);
		echojson(array_merge($res,$res2));
	}
	public function home(){
		$admin = r_user($this->gobaluser);
		$isAdmin=true;
		$serviceOption='';
		$supplierOption='';
		$gasOption='';
		$classes = new \app\controller\model\Classes();
		if($admin['ctype']==2){
			$isAdmin=false;
			$gasOption = $classes->rMyGasToOption(0,$admin['serviceIDS'])[0];
		}
		if($admin['ctype']==1){
			$isAdmin=false;
			$serviceOption = $classes->rMyServiceToOption(0,$admin['serviceIDS'])[0];
		}
		if($admin['ctype']==0){
			$serviceOption = $classes->rAllServiceToOption()[0];
			$supplierOption = $classes->rSupplierToOption()[0];
		}
		return view("admin/home")->assign(['supplier'=>$supplierOption,'gas'=>$gasOption,'isAdmin'=>$isAdmin,'ctype'=>$admin['ctype'],'service'=>$serviceOption]);
	}
	public function delGroup(){
		$uid = request()->param("uid");
		$id = request()->param("id");
		$re = DB::name($this->tables->authGroupAccess)->where("uid",$uid)->where("group_id",$id)->delete();
		if($re){

		}else{
			echojson([],1,'记录不存在');
		}
		echojson();
	}
	public function userGroupAdd(){
		$id = request()->param("id");
		$re = [];
		if($id>0){
			$re = r_one("admin_group","id=$id");
		}
		return view("adminauth/userGroupAdd")->assign('re',$re);
	}
	public function userGroup(){
		return view("adminauth/userGroup");
	}
	public function userGroupSave(){
		$id=request()->param("id");
		$title=request()->param("title");
		if(strlen($title)<1){echojson([],1,'组名称不可为空');}
		if($id>0){
			$re = r_one("admin_group","id=$id");
			if(!$re){echojson([],1,'id错误');}
			$re = r_one("admin_group","id<>$id and title='$title'");
			if($re){echojson([],1,'组名称重复');}
			$up = DB::name("admin_group")->where("id",$id)->update(['title'=>$title]);
		}else{
			$up = DB::name("admin_group")->insert(['title'=>$title]);
		}
		if($up){echojson();}else{echojson([],1,'操作失败');}
	}
	public function userGroupList(){
		$page=request()->param("page");
		$limit=request()->param("limit");
		$title=request()->param("title");
		$sql = DB::name("admin_group");
		$limit<10?$limit=10:'';
		if($title!=''){$sql=$sql->where("title","like","%$title%");}
		$count = (clone $sql)->count();
		$pages = ceil($count/$limit);
		$pages<1?$pages=1:'';
		$page>$pages?$page=$pages:'';
		$res = $sql->order("id desc")->limit(($page-1)*$limit,$limit)->select();
		pagejson($res,0,'',$count);
	}
	public function scanQRCode(){
		$url="https://api.weixin.qq.com/cv/img/qrcode?img_url=https%3A%2F%2Flzk.moffice365.cn%2Fuploads%2Fqrcode_55.jpg&access_token=47_eLTIvMv1VkBzmPV3Q5vlY5UCWd1LPZn4Oo8H9_t7YkBonitWCHQyZqmlpEzSGKZwcP-hPmSKYcycuNM8JOFGZ7sytRci63p4cEL89gTmPoNs6NB_Ja1tUpzFZodP6I6l6fwDbqKmKmu99RPrVBCbAAALRS";
		$options = array(
			'http' => array(
				'method' => 'POST',
				'header' => 'Content-type:application/x-www-form-urlencoded',
				'timeout' => 15 * 60 // 超时时间（单位:s）
			)
		);
		$context = stream_context_create($options);
		$re=file_get_contents($url,false, $context);
		echo $re;
	}
	public function qrcode(){//获取推广二维码
		$id=request()->param("id")*1;
		$savename="uploads/qrcode_$id.jpg";
		if(file_exists($savename)){
			echojson(['img'=>$savename],0);
		}
		$token=DB::name("token")->where("title",'token')->where("uptime",">",time()-7000)->find();
		if($token){
			$token=$token['content'];
		}else{
			$token=gettoken();
		}
		$postarr=['scene'=>$id];
		$postarr=json_encode($postarr);
		$re=$this->send_post("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$token",$postarr);
		if($re!=false){

			$file = fopen($savename,"w");//创建件准备写入，文件名xcxcode/wxcode1.jpg为自定义
			fwrite($file,$re);//写入
			fclose($file);//关闭
			echojson(['img'=>$savename],0);
		}else{
			echojson($re,1);
		}

	}
	protected function send_post($url, $post_data="") {

//        $postdata = http_build_query($post_data);
//        $options = array(
//            'http' => array(
//                'method' => 'POST',
//                'header' => 'Content-type:application/x-www-form-urlencoded',
//                'content' => $postdata,
//                'timeout' => 15 * 60 // 超时时间（单位:s）
//            )
//        );
//        $context = stream_context_create($options);
//        $result = file_get_contents($url, false, $context);


		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);

//报错行
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

		$result = curl_exec($ch);


		return $result;
	}
	public function authgroup(){//权限组列表
		$uid=request()->param("uid")*1;
		$uid<1?0:$uid;
		return view("adminauth/authgroup")->assign("uid",$uid);
	}
	public function juesebaocun(){//保存角色 adminauth/juesebaocun
		$uid=request()->param("id")*1;
		$like=request()->param("like");
		$uparr=[];
		if(!isset($like)){
			$like=[];
		}
		if(in_array('xiugai',$like)){$uparr['xiugai']=1;}else{$uparr['xiugai']=0;}
		$uparr['zhongshen']=0;
		if(in_array('chushen',$like)){$uparr['zhongshen']=1;}
		if(in_array('fushen1',$like)){$uparr['zhongshen']=2;}
		if(in_array('fushen2',$like)){$uparr['zhongshen']=3;}
		if(in_array('fushen3',$like)){$uparr['zhongshen']=4;}
		if(in_array('yujin',$like)){$uparr['yujin']=1;}else{$uparr['yujin']=0;}
		$re=DB::name("admin")->where("id",$uid)->update($uparr);
		if($re){echojson([],0,"修改成功");}else{echojson([],1,"未更新");}
	}
	public function juese(){//用户角色页面 adminauth/juese
		$uid=request()->param("uid")*1;
		$user=getuser($uid)[2];
		$juese=[];
		if($user['zhongshen']==1){$juese[]="chushen";}
		if($user['xiugai']==1){$juese[]="xiugai";}
		if($user['zhongshen']==2){$juese[]="fushen1";}
		if($user['zhongshen']==3){$juese[]="fushen2";}
		if($user['zhongshen']==4){$juese[]="fushen3";}
		if($user['yujin']==1){$juese[]="yujin";}
		return view()->assign(['re'=>$user,'juese'=>$juese]);
	}
	public function user(){//用户页面
		return view("adminauth/user")->assign(['zu'=>r_group()]);
	}
	public function adduser(){
		$uid=request()->param("uid")*1;
		if($uid<1){
			$user['username']="";
			$user['password']="";
			$user['password2']="";
			$user['pwdtxt']="";
			$user['fullname']="";
			$user['pathid']="";
			$user['pathid2']="";
			$user['phone']="";
			$user['address']="";
			$user['company']="";
			$user['email']="";
			$user['status']="";
			$user['serviceIDS']="[]";
			$user['ctype']=0;
		}else{
			$user=DB::name("admin")->field("id,username,password,fullname,phone,address,company,email,status,pathid,pathid2,serviceIDS,ctype")->where("id",$uid)->find();
			if(!$user)echojson([],1,'ID错误');
			$user['serviceIDS']="[".$user['serviceIDS']."]";
		}
		return view()->assign('user',$user);
	}
	public function getServices(){
		$type = request()->param("type");
		if($type=='gas'){
			$res = DB::name("gas")->field("id as value,name as title,localStatus,city,country")->select()->toArray();
			foreach ($res as &$v){
				if($v['localStatus']!=1){
					$v['disabled']=true;
				}
				$v['title']=$v['title']." - ".$v['city'].$v['country'];
			}
		}else{
			$res = DB::name("service")->field("id as value,title,status")->select()->toArray();
			foreach ($res as &$v){
				if($v['status']==-1){
					$v['disabled']=true;
				}
			}
		}

		echojson($res);
	}
	public function task(){
		$id=request()->param("id")*1;
		$re=DB::name("admin")->where("id",">",0)->update(['dangqian'=>0]);
		$re=DB::name("admin")->where("id",$id)->update(['dangqian'=>1]);
		if($re){
			echojson([],0,'设置成功');
		}else{
			echojson([],1,'设置失败');
		}
	}
	public function adduserpost(){
		$uid=request()->param("uid")*1;
		$username=request()->param("username");
		$fullname=request()->param("fullname");
		$password=request()->param("password");
		$password2=request()->param("password2");
		$phone=request()->param("phone");
		$address=request()->param("address");
		$yincang=request()->param("yincang");
		$pathid=request()->param("pathid");
		$pathid2=request()->param("pathid2");
		$company=request()->param("company");
		$serviceIDS=request()->param("serviceIDS");
		$email=request()->param("email");
		$ctype=request()->param("ctype");
		$arr=['pathid'=>$pathid,'pathid2'=>$pathid2,'username'=>$username,'fullname'=>$fullname,'phone'=>$phone,'address'=>$address,'company'=>$company,'email'=>$email,'status'=>$yincang,'ctype'=>$ctype];
		if($serviceIDS!=''){
			$serviceIDS = json_decode($serviceIDS,true);
			$temArr=[];
			foreach ($serviceIDS as $v){
				$temArr[] = $v['value'];
			}
			$arr['serviceIDS'] = implode(",",$temArr);
		}
		$arr['password']=md5($password);
		$arr['password2']=md5($password2);
//        $arr['pwdtxt']=$password2;
		if($uid>0){
			//修改流程
			if($password=="" || $password==null){unset($arr['password']);}
			if($password2=="" || $password2==null){unset($arr['password2']);unset($arr['pwdtxt']);}
			$re=DB::name("admin")->where("id",$uid)->update($arr);
		}else{
			if($password==""){
				echojson([],1,'请输入密码');
			}
			if($password2==""){
//                echojson([],1,'请输入个人密码');
			}
			$re=DB::name("admin")->where("username",$username)->find();
			if($re){
				echojson([],1,'用户名重复');
			}
			//增加用户
			$re=DB::name("admin")->insert($arr);
		}
		if($re){
			echojson([],0,'操作成功');
		}else{
			echojson([],1,'操作失败或未更新');
		}
	}
	public function usersave(){//保存权限组到用户
		$uid=request()->param("uid")*1;
		$ids=request()->param("ids");
		$ids = json_decode($ids,true);
		foreach ($ids as $v){
			$res=DB::name("auth_group_access")->where("uid",$uid)->where("group_id",$v)->find();
			if($res){

			}else{
				DB::name("auth_group_access")->insert(['uid'=>$uid,'group_id'=>$v]);
			}
		}
		DB::name("auth_group_access")->where("uid",$uid)->whereNotIn("group_id",$ids)->delete();
		echojson([],0,"添加成功");
	}
	public function userlist(){//用户页面数据
//        $res=DB::name("admin")->field("id,fullname")->where("status",1)->select();
//        echojson($res);
		$group=request()->param("group");
		$t=request()->param("t");
		$pathid=request()->param("pathid");
		$only_fa=request()->param("only_fa");
		$pathid2=request()->param("pathid2");
		$fullname=request()->param("fullname");
		$yincang=request()->param("yincang")*1;
		$page=request()->param("page")*1;
		$limit=request()->param("limit")*1;
		$page<1?1:$page;
		$re=DB::name("admin");
		if($group>0){
			$ids=DB::name("auth_group_access")->field("uid as id")->where("group_id",$group)->select();
			$idsarr=[];
			foreach ($ids as $v){
				$idsarr[]=$v['id'];
			}
			$re=$re->where("id","in",$idsarr);
		}
		if($yincang==2){
			$re=$re->where("status",0);
		}elseif($yincang==-1){
			$re=$re->where("status",-1);
		}else{
			$re=$re->where("status",1);
		}
		if($fullname!=''){
			$re=$re->where("fullname",'like',"%$fullname%");
		}
		if($pathid!=''){
			$res=DB::name("admin")->where("fullname",'like',"%$pathid%")->select();
			$inids=[];
			if ($res){
				foreach ($res as $v){
					$inids[] = $v['id'];
				}
			}
			$re = $re->whereIn("pathid",$inids);
		}
		if($pathid2!=''){
			$res=DB::name("admin")->where("fullname",'like',"%$pathid2%")->select();
			$inids=[];
			if ($res){
				foreach ($res as $v){
					$inids[] = $v['id'];
				}
			}
			$re = $re->whereIn("pathid2",$inids);
		}
		if($only_fa==1){
			$res=DB::name("admin")->where("pathid2",">",0)->select();
			$inids=[];
			if ($res){
				foreach ($res as $v){
					$inids[] = $v['pathid2'];
				}
			}
			$re = $re->whereIn("id",$inids);
		}
		$re2=  clone $re;
		$count=$re2->count();
		if($count<1){
			pagejson([],0,"",0);
		}
		$pages=ceil($count/$limit);
		$page>$pages?$pages:$page;
		$re=$re->limit(($page-1)*$limit,$limit);
		$lists=$re->select();
		$lists=$lists->all();
		if($t == 'points'){
			//如果是积分页 就需要获取当月积分
			$month = request()->param("month");
			if($month==''){
				$month = date("Y-m");
			}
			$year = date("Y",strtotime($month));
			$month = date("m",strtotime($month));
		}
		foreach ($lists as $k=>$v){
			$users=DB::name("admin")->where("id",$v['pathid'])->find();
			$users2=DB::name("admin")->where("id",$v['pathid2'])->find();
			if($t == 'points'){
				//如果是积分页 就需要获取当月积分
				$lists[$k]['points'] = r_user_points($v['id'],$year,$month)[0];
			}
			if($users){
				$lists[$k]['pathid']=$users['fullname'];
			}
			if($users2){
				$lists[$k]['pathid2']=$users2['fullname'];
			}
		}
		pagejson($lists,0,"",$count);
	}
	public function authlist(){//权限列表页面
		$gid=request()->param("gid")*1;
		$gid<1?0:$gid;
		return view("adminauth/authlist")->assign("gid",$gid);
	}
	public function authgrouplist(){//权限组页面数据
		$label=request()->param("label");
		$uid=request()->param("id")*1;
		$userID=request()->param("uid")*1;
		$inIDS = [];
		if($userID>0){
			$haveAuth = DB::name("auth_group_access")->where("uid",$userID)->select();
			foreach ($haveAuth as $v){
				$inIDS[] = $v['group_id'];
			}
		}
		if($label===false || $uid<1){
			$res=DB::name("auth_group")->where("status",1)->select();
		}else{

			$temarr=[];
			$userauth=DB::name("auth_group_access")->where("uid",$uid)->select();
			foreach ($userauth as $v){
				$temarr[]=$v['group_id'];
			}
			if($label==0){
				$res=DB::name("auth_group")->where("id","not in",$temarr)->where("status",1)->select();
			}else{
				$res=DB::name("auth_group")->where("id","in",$temarr)->where("status",1)->select();
			}
		}
		$res = $res->all();
		foreach ($res as $k => $v){
			if(in_array($v['id'],$inIDS)){
				$res[$k]['LAY_CHECKED']=true;
			}
		}
		echojson($res);
	}
	public function authruleedit(){
		$id=request()->param("gid");
		$pathid=request()->param("pathid");
		$tags=request()->param("tags");
		$action=request()->param("action");
		$classty=request()->param("classty");
		$sortid=request()->param("sortid");
		$writeLog=request()->param("writeLog");
		$re=DB::name("auth_rule")->where("id",$id)->find();
		if($re){
			$up=DB::name("auth_rule")->where("id",$id)->update(['name'=>$action,'title'=>$tags,'name'=>$action,'classty'=>$classty,'sortid'=>$sortid,'log'=>$writeLog=='true'?1:0]);
			if($up){
				echojson([],0,"修改成功");
			}else{
				echojson([],1,"修改失败");
			}
		}else{
			echojson([],1,"记录不存在");
		}
	}
	public function tagsform(){//权限添加页面
		$pathid=request()->param("pathid")*1;
		$ty=request()->param("ty")*1;
		$gid=request()->param("gid")*1;
		if($gid>0){
			//修改程序
			$rule=r_rule($gid);
			if($rule){
				return view("adminauth/tagsform")->assign(["id"=>$pathid,'ty'=>$ty,'rule'=>$rule,'gid'=>$gid]);
			}
		}
		return view("adminauth/tagsform")->assign(["id"=>$pathid,'ty'=>$ty,'gid'=>$gid]);
	}
	public function tagssave(){//保存权限添加
		$tags=request()->param("tags");
		$action=request()->param("action");
		$pathid=request()->param("pathid");
		$classty=request()->param("classty");
		$sortid=request()->param("sortid");
		$writeLog=request()->param("writeLog");
		$re=DB::name("auth_rule")->where("name",$action)->find();
		if($action==""){
			$re=false;
		}
		if(!$re){
			$arr=[
				'name'=>$action,
				'title'=>$tags,
				'pathid'=>$pathid,
				'classty'=>$classty,
				'sortid'=>$sortid,
				'log'=>$writeLog=='true'?1:0,
			];
			$re=DB::name("auth_rule")->insert($arr);
			if($re){
				echojson([],0,"添加成功");
			}else{
				echojson([],1,"添加失败");
			}
		}else{
			echojson([],1,"重复记录");
		}

	}
	public function authgroupsave(){//保存权限组添加
		$str=request()->param("str");
		$gid=request()->param("gid")*1;
		$ids=[];
		foreach (json_decode($str,true) as $v){
			$ids[]=$v['id'];
			foreach ($v['children'] as $v2){
				$ids[]=$v2['id'];
				if(isset($v2['children'])){
					foreach ($v2['children'] as $v3){
						$ids[]=$v3['id'];
					}
				}

			}
		}

		if(count($ids)>0){
			$re=DB::name("auth_group")->where("id",$gid)->find();
			if($re){
				DB::name("auth_group")->where("id",$gid)->update(['rules'=>implode(",",$ids),'status'=>1]);
			}else{
				echojson([],1,"修改失败");
			}
		}
		echojson();
	}
	public function addgroup(){//保存权限组名称
		$tags=request()->param("tags");
		$re=DB::name("auth_group")->where("title",$tags)->find();
		if(!$re){
			DB::name("auth_group")->insert(['title'=>$tags]);
		}else{
			echojson([],1,"重复记录");
		}
		echojson();
	}
	public function authlistdata(){//权限列表数据
		$gid=request()->param("gid")*1;
		$allOpen=request()->param("allOpen");
		$ids=[];
		if($gid>0){
			$res=DB::name("auth_group")->where("id",$gid)->where("status",1)->find();
			$ids=explode(",",$res['rules']);
		}
		$res=DB::name("auth_rule")->where("pathid",0)->where("status",1)->order("sortid desc")->select();
		$rearr2=[];
		foreach ($res as $v){
			$rearr=[];
			$rearr['title']=$v['title']." - ".$v['classty'];
			if($v['log']==1){
				$rearr['title'] .= "<font color='red'>志</font>";
			}
			$rearr['id']=$v['id'];
			$rearr['spread']=true;
			$rearr['classty']=$v['classty'];
			$res2=DB::name("auth_rule")->where("pathid",$v['id'])->where("status",1)->order("sortid desc")->select();
			if($res2){

				foreach ($res2 as $v2){
					$temarr=[];
					$temarr['title']=$v2['title']." - ".$v2['name'].' - '.$v2['classty'];
					if($v2['log']==1){
						$temarr['title'] .= "<font color='red'>志</font>";
					}
					$temarr['id']=$v2['id'];
					$rearr['classty']=$v2['classty'];
					if(in_array($v2['id'],$ids)){
						$temarr['checked']=true;
					}else{
						$temarr['checked']=false;
					}
					if($allOpen == 1){
						$rearr['spread']=true;
					}
					//读取第三级 如果第三级有checked=false  那么第二级就不选择
					$res3=DB::name("auth_rule")->where("pathid",$v2['id'])->where("status",1)->order("sortid desc")->select();
					if($res3){
						$checked=true;
						foreach ($res3 as $v3){
							$temarr3=[];
							$temarr3['title']=$v3['title']." - ".$v3['name'].' - '.$v3['classty'];
							if($v3['log']==1){
								$temarr3['title'] .= "<font color='red'>志</font>";
							}
							$temarr3['id']=$v3['id'];
							$temarr3['classty']=$v3['classty'];
							if(in_array($v3['id'],$ids)){
								$temarr3['checked']=true;
							}else{
								$checked=false;
								$temarr3['checked']=false;
							}
							$temarr['children'][]=$temarr3;
						}
						if($allOpen == 1){
							$temarr['spread']=true;
						}
						if($checked==false){
							$temarr['checked']=false;
						}
					}
					//
					$rearr['children'][]=$temarr;
				}
			}
			$rearr2[]=$rearr;
		}
		echojson($rearr2);
	}
}
